package com.baidu.location.demo;


import static com.util.util.setSize;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.entity.Authority;
import com.entity.Friends;
import com.entity.Login;
import com.entity.Response;
import com.entity.User;
import com.fragment.GpsFragment;
import com.fragment.MessageFragment;
import com.fragment.MineFragment;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.service.HubService;
import com.service.ScreenService;
import com.util.DialogUtil;
import com.util.FileUtil;
import com.util.HttpUtils;
import com.util.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import kr.co.namee.permissiongen.internal.Utils;

/**
 * 后台定位demo示例
 */
public  class MainActivity extends CheckPermissionsActivity  {
    public static int width;
    public static int height;
    public static int dpi;
    public static User user=null;
    public static List<Friends> friends=new ArrayList<>();
    public static GpsFragment gpsFragment;
    public static MessageFragment messageFragment;
    public static MineFragment mineFragment;
    private LinearLayout dataView;
    private LinearLayout util1;
    private LinearLayout util2;
    private LinearLayout util3;
    private Display display;
    public static Thread login;
    private ImageView mineBut;
    private ImageView messageBut;
    private ImageView gpsBut;
    public  static Thread friendsListThread;
    public static FragmentManager fragmentManager;
    public static Fragment fragment=null;
    public static String versionName;//版本号
    @RequiresApi(api = Build.VERSION_CODES.M)
    @SuppressLint({"CommitTransaction", "WrongViewCast"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String data= null;
        try {
            data = FileUtil.Read(this,"user.json" );
        } catch (IOException e) {
            e.printStackTrace();
            startActivity(new Intent(this,LoginActivity.class));
        }
        if(data.isEmpty()){
            startActivity(new Intent(this,LoginActivity.class));
            return;
        }

        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            versionName=info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        setContentView(R.layout.activity_main);
           String userJson=getIntent().getStringExtra("user");
           if(userJson==null||userJson.isEmpty()){
               String finalData = data;
               login= new Thread(){
                   @Override
                   public void run() {
                       super.run();
                       user= JSONObject.parseObject(finalData,new TypeReference<User>(){});
                       if(!LoginActivity.isCreate){
                           Response<Login> json= JSONObject.parseObject(HttpUtils.Post("Login/Login?user="+user.getUserNumber()+"&pass="+user.getPassWord(),""),new TypeReference<Response<Login>>(){});
                           if(json.getStatusCode()==200){
                               user= json.getValue().getUser();
                               Authority.setAuthorization(json.getValue().getToken());
                               try {
                                   FileUtil.Save(MainActivity.this,"user.json",JSONObject.toJSONString(json.getValue().getUser()));
                               } catch (IOException e) {
                                   e.printStackTrace();
                               }
                           }else{
                               FileUtil.Delete(MainActivity.this,"user.json");
                               MainActivity.this.runOnUiThread(() -> startActivity(new Intent(MainActivity.this,LoginActivity.class)));
                           }
                       }
                   }
               };
               login.start();
           }else{
               user=JSONObject.parseObject(userJson,User.class);
           }


        messageFragment=MessageFragment.newInstance();
        mineFragment=MineFragment.newInstance();
        mineBut=findViewById(R.id.mineBut);
        messageBut=findViewById(R.id.messageBut);
        gpsBut=findViewById(R.id.gpsBut);
        mineBut.setOnClickListener(view -> {
            if(fragment.equals(mineFragment))return;
            fragmentManager= getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .hide(fragment)
                    .show(mineFragment)
                    .commit();
            fragment=mineFragment;

        });
        messageBut.setOnClickListener(view -> {
            if(fragment.equals(messageFragment))return;
            fragmentManager= getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .hide(fragment)
                    .show(messageFragment)
                    .commit();
            fragment=messageFragment;

        });
        gpsBut.setOnClickListener(view -> {
            if(fragment.equals(gpsFragment))return;
            fragmentManager= getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .hide(fragment)
                    .show(gpsFragment)
                    .commit();
            fragment=gpsFragment;

        });
        display = getWindowManager().getDefaultDisplay();
        dataView= findViewById(R.id.dataView);
        util1= findViewById(R.id.util1);
        util2= findViewById(R.id.util2);
        util3= findViewById(R.id.util3);
        if(display.getHeight()>3000){

            setSize(dataView,0, (int) (display.getHeight()*0.92));
        }else if(display.getHeight()>2000){
            setSize(dataView,0, (int) (display.getHeight()*0.87));
        }else{
            setSize(dataView,0, (int) (display.getHeight()*0.85));
        }
        setSize(util1,display.getWidth()/3,0);
        setSize(util2,display.getWidth()/3,0);
        setSize(util3,display.getWidth()/3,0);
        gpsFragment=GpsFragment.newInstance();
        fragment=gpsFragment;
        fragmentManager= getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .add(R.id.dataView,messageFragment)
                .add(R.id.dataView,mineFragment)
                .add(R.id.dataView,gpsFragment)
                .hide(messageFragment)
                .hide(mineFragment)
                .show(gpsFragment)
                .commit();
        startService(new Intent(this, HubService.class));
        friendsListThread=new Thread(){
            @Override
            public void run() {
                super.run();
                GetFriendsList(MainActivity.this);
            }
        };
        friendsListThread.start();
    }
    public static void GetFriendsList(Activity activity){
        try {
            if(login!=null) login.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String json= HttpUtils.Get("Friends/GetFriendsList");
        Response<List<Friends>> data=JSONObject.parseObject(json,new TypeReference<Response<List<Friends>>>(){});
        if(data.getStatusCode()==200){
            friends=data.getValue();
        }else{
            DialogUtil.CreateDoalog(activity,data.getMessage(),0, QMUITipDialog.Builder.ICON_TYPE_FAIL);
        }
    }
    @SuppressLint("NewApi")
    @Override
    public void onActivityResult(int requestCode,int resultCode,Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==222&&resultCode==-1){
            WindowManager windowManager=this.getWindowManager();
            if(windowManager!=null){
                DisplayMetrics displayMetrics=new DisplayMetrics();
                windowManager.getDefaultDisplay().getMetrics(displayMetrics);
                width=displayMetrics.widthPixels;
                height=displayMetrics.heightPixels;
                dpi=displayMetrics.densityDpi;
            }
            Intent i=new Intent(this, ScreenService.class);
            i.putExtra("code",resultCode);
            i.putExtra("data",data);
            i.putExtra("width",width);
            i.putExtra("height",height);
            i.putExtra("dpi",dpi);
            startForegroundService(i);
        }
        if(resultCode==0){
            DialogUtil.CreateDoalog(this,"您拒绝了权限将无法使用特殊功能",0,QMUITipDialog.Builder.ICON_TYPE_NOTHING);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        HubService.hubConnection.remove("data");
        HubService.hubConnection.stop();
        new Thread(){
            @Override
            public void run() {
                super.run();
                HttpUtils.Delete("Login/Exit","");
            }
        }.start();
        finish();
    }
}
